package concurrent

import (
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"time"
)

func Hello() {
	fmt.Println("hello")
}

func TestGoRoutine1() {
	//启动go routine  由go运行时调度器异步执行
	go Hello()
	fmt.Println("test1")
	time.Sleep(time.Second)
}

//waitgroup为值类型，使用指针传递
func hello(i int, wait *sync.WaitGroup) {
	defer wait.Done()
	fmt.Println("go routine " + strconv.Itoa(i))
}

func TestGoroutine2() {
	//waitgroup
	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go hello(i, &wg)
	}

	wg.Wait()
}

func TestGoroutine(core int) {
	a := func() {
		for i := 1; i < 1000; i++ {
			fmt.Println("A:", i)
			//time.Sleep(time.Millisecond *  50)
		}
	}

	b := func() {
		for i := 1; i < 1000; i++ {
			fmt.Println("B:", i)
			//time.Sleep(time.Millisecond *  50)
		}
	}

	c := func() {
		for i := 1; i < 1000; i++ {
			fmt.Println("C:", i)
			//time.Sleep(time.Millisecond *  50)
		}
	}

	d := func() {
		for i := 1; i < 1000; i++ {
			fmt.Println("D:", i)
			//time.Sleep(time.Millisecond *  50)
		}
	}

	//指定逻辑核心数量
	runtime.GOMAXPROCS(core)

	go a()
	go b()
	go c()
	go d()

	time.Sleep(time.Second)
}
